<template>
  <div class="elderly-management">
    <div class="page-header">
      <div class="header-left">
        <h2>老人档案管理</h2>
        <p>管理所有老人的基本信息、健康记录和用药记录</p>
      </div>
      
      <el-button type="primary" @click="showAddDialog = true,isEdit=false,resetForm()">
        <el-icon><Plus /></el-icon>
        添加老人档案
      </el-button>
    </div>
    
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        
        <el-form-item label="年龄范围">
          <el-input-number
            v-model="searchForm.minAge"
            :min="0"
            :max="150"
            placeholder="最小年龄"
            style="width: 120px"
          />
          <span style="margin: 0 8px">-</span>
          <el-input-number
            v-model="searchForm.maxAge"
            :min="0"
            :max="150"
            placeholder="最大年龄"
            style="width: 120px"
          />
        </el-form-item>
        
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable style="width: 120px">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>老人档案列表 (共 {{ total }} 条记录)</span>
          <div class="table-actions">
            <el-button size="small" @click="batchDelete" type="danger">批量删除</el-button>
          </div>
        </div>
      </template>
      
        <el-table
        :data="elderlyStore.elderlyList"
        v-loading="loading"
        style="width: 100%"
        stripe
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: '600' }"
        @selection-change="handleSelectionChange"
        class="scrollable-table"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" width="120" sortable>
          <template #default="{ row }">
            <span class="elderly-name">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" sortable>
          <template #default="{ row }">
            <span class="age-text">{{ row.age }}岁</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.sex === '男' ? 'primary' : 'success'" size="small">
              {{ row.sex }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="140">
          <template #default="{ row }">
            <span class="phone-text">{{ row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="address-text">{{ row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column label="紧急联系人" width="180">
          <template #default="{ row }">
            <div class="contact-info">
              <div class="contact-name">{{ row.emergencyContact.name }}</div>
              <div class="contact-phone">{{ row.emergencyContact.phone }}</div>
              <div class="contact-relation">{{ row.emergencyContact.relationship }}</div>
            </div>
          </template>
        </el-table-column>
        
       <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="editElderly(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteElderly(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-card>
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    
    
    <!-- 添加/编辑老人对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="isEdit ? '编辑老人档案' : '添加老人档案'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="elderlyFormRef"
        :model="elderlyForm"
        :rules="elderlyRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="elderlyForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="elderlyForm.age"
                :min="0"
                :max="150"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="elderlyForm.sex" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="elderlyForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="地址" prop="address">
          <el-input v-model="elderlyForm.address" placeholder="请输入地址" />
        </el-form-item>
        
        <el-divider content-position="left">紧急联系人信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="emergencyContact.name">
              <el-input v-model="elderlyForm.emergencyContact.name" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="emergencyContact.phone">
              <el-input v-model="elderlyForm.emergencyContact.phone" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="关系" prop="emergencyContact.relationship">
          <el-input v-model="elderlyForm.emergencyContact.relationship" placeholder="请输入与老人的关系" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveElderly" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useElderlyStore, type Elderly } from '@/stores/elderly'
import { addElderly, getAllElderly, updateElderly, deleteElderly as deleteElderlyApi,searchElderly} from '@/api/elderlyInfo/elderlyInfo'
import { onMounted } from 'vue'
const router = useRouter()
const elderlyStore = useElderlyStore()

const loading = ref(false)
const saving = ref(false)
const showAddDialog = ref(false)
const isEdit = ref(false)
const elderlyFormRef = ref<{ validate: (callback: (valid: boolean) => void) => void }>()
const currentPage = ref(1)
const pageSize = ref(20)
const selectedElderly = ref<Elderly[]>([])

const searchForm = reactive({
  name: '',
  minAge: null as number | null,
  maxAge: null as number | null,
  gender: ''
})

const elderlyForm = reactive({
  id: '',
  name: '',
  age: 0,
  sex: '男' as '男' | '女',
  phone: '',
  address: '',
  emergencyContact: {
    name: '',
    phone: '',
    relationship: ''
  },
  medicalHistory: [] as string[],
  allergies: [] as string[]
})

const elderlyRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  'emergencyContact.name': [{ required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }],
  'emergencyContact.phone': [{ required: true, message: '请输入紧急联系人电话', trigger: 'blur' }],
  'emergencyContact.relationship': [{ required: true, message: '请输入关系', trigger: 'blur' }]
}

const handleSearch =async () => {
  const repsone  = await searchElderly(searchForm)
  elderlyStore.setElderlyList(repsone.data)
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.minAge = null
  searchForm.maxAge = null
  searchForm.gender = ''
  currentPage.value = 1
  fetchElderlyData()
}

const handleSelectionChange = (selection: Elderly[]) => {
  selectedElderly.value = selection
}


const batchDelete = async () => {
  if (selectedElderly.value.length === 0) {
    ElMessage.warning('请先选择要删除的老人')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedElderly.value.length} 位老人档案吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    selectedElderly.value.forEach(elderly => {
      deleteElderlyApi(elderly.id)
    })
    
    ElMessage.success('批量删除成功')
    selectedElderly.value = []
    await fetchElderlyData()
  } catch {
    // 用户取消
  }
}

const viewDetail = (elderly: Elderly) => {
  router.push(`/admin/elderly/${elderly.id}`)
}

const editElderly = (elderly: Elderly) => {
  isEdit.value = true
  Object.assign(elderlyForm, elderly)
  showAddDialog.value = true
}

const deleteElderly = async (elderly: Elderly) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除老人 ${elderly.name} 的档案吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteElderlyApi(elderly.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await fetchElderlyData() // 重新获取数据
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch {
    // 用户取消
  }
}

const saveElderly = async () => {
  try {
    saving.value = true
    elderlyFormRef.value?.validate(async (valid: boolean) => {
      if (valid === true) {
        let response
        if (isEdit.value) {
          // 更新现有老人
          response = await updateElderly(elderlyForm.id, elderlyForm)
        } else {
          // 添加新老人
          response = await addElderly(elderlyForm)
        }
        
        if (response.code === 200) {
          ElMessage.success('保存成功')
          await fetchElderlyData() // 重新获取数据
          showAddDialog.value = false
          resetForm()
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      }
    })
  } catch (error) {
    ElMessage.error('保存过程中出错')
    console.error(error)
  } finally {
    saving.value = false
  }
}
onMounted(() => {
  fetchElderlyData()
})
const total =ref()
const fetchElderlyData = async () => {
  loading.value = true;
  try {
    const response = await getAllElderly(currentPage.value, pageSize.value);
    console.log('API响应数据:', response.data); // 调试日志
    total.value =response.data.total
    if (response.code === 200) {
      console.log('设置Pinia数据');
      elderlyStore.setElderlyList(response.data.rows || []);
      console.log('Pinia存储后的数据:', elderlyStore.elderlyList); // 调试日志
    }
  } catch (error) {
    console.error('获取老人数据错误:', error);
    ElMessage.error('获取老人数据失败');
  } finally {
    loading.value = false;
  }
};


const resetForm = () => {
  Object.assign(elderlyForm, {
    id: '',
    name: '',
    age: 0,
    gender: '男',
    phone: '',
    address: '',
    emergencyContact: {
      name: '',
      phone: '',
      relationship: ''
    },
    medicalHistory: [],
    allergies: []
  })
  isEdit.value = false
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchElderlyData()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchElderlyData()
}
</script>

<style scoped>
.elderly-management {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding: 0 4px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  margin: 0;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.elderly-name {
  font-weight: 500;
  color: #333;
}

.age-text {
  color: #409eff;
  font-weight: 500;
}

.phone-text {
  color: #666;
  font-family: monospace;
}

.address-text {
  color: #666;
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.contact-name {
  font-weight: 500;
  color: #333;
}

.contact-phone {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.contact-relation {
  font-size: 12px;
  color: #999;
}

.medical-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}
/* 表格滚动区域样式 */
.scrollable-table {
  flex: 1;
  overflow: auto;
}

/* 确保表格容器有固定高度 */
.table-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 200px; /* 设置最小高度 */
  max-height: calc(100vh - 200px); /* 根据视口高度动态调整 */
  overflow: hidden; /* 隐藏外部滚动条 */
}
.contact-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-height: 100px;
  overflow-y: auto;
  padding-right: 4px;
}

/* 滚动条样式 */
.contact-info::-webkit-scrollbar {
  width: 4px;
}

.contact-info::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 2px;
}
.elderly-management {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止双层滚动条 */
}

.page-header, .search-card {
  flex-shrink: 0; /* 防止头部被压缩 */
}
@media (max-width: 1200px) {
  .table-card :deep(.el-card__body) {
    max-height: calc(100vh - 280px);
  }
}

@media (max-width: 768px) {
  .table-card :deep(.el-card__body) {
    min-height: 300px;
    max-height: calc(100vh - 250px);
  }
  
  .contact-info {
    max-height: 80px;
  }
}
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 隐藏内部溢出 */
}
.contact-info::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
/* 表格内部滚动 */
.scrollable-table :deep(.el-table__body-wrapper) {
  overflow-x: auto;
  overflow-y: auto;
}

/* 固定表头 */
.scrollable-table :deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 2;
}
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-header {
    margin-bottom: 20px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    margin-bottom: 16px;
  }
  
  .header-left h2 {
    font-size: 20px;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style> 